<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
    <div class="container">
        <import-dir-img ref="imgDirService" :row="row" @result="imgResultAction"></import-dir-img>
        <import-imgs ref="imgService" :row="row" @result="importImgsResultAction"></import-imgs>
        <viewer-show-img :view-show="viewShow" :show-img-list="showImgList" ref="viewerShowImg" @close="showImgList=[]"></viewer-show-img>
        <div class="opt-area-02" v-if="params.type != 'accept'">
            <div class="left-con">
                录入总数: <span>{{barData.totalNum}} 条</span> |
                有图片数据: <span>{{barData.exitTNum}} 条</span> |
                没有图片数据: <span>{{barData.exitFNum}} 条</span> |
                数量不符数据: <span>{{barData.nopassNum}} 条</span> |
                数量符合数据: <span>{{barData.passNum}} 条</span> |
                页数总和: <span>{{pageNum}} 页</span>
            </div>
        </div>
        <vxe-toolbar>
            <template v-slot:buttons>
                <Button v-has="'CL_return'" type="default" class="mp10" @click="backAction">返回</Button>
                <template v-if="(row.state == 1 || row.state == 4) && params.type != 'accept'">
                    <Button v-has="'CL_xinzengyitiao'" type="success" class="mp10" @click="insertEvent(row)">新增一条
                    </Button>
                    <Button v-has="'CL_delete'" type="error" class="mp10" @click="deleteRowList">删除选中</Button>
                    <Button v-has="'CL_tupiandaoru'" type="primary" class="mp10" @click="uploadImgDirAll">图片批量导入
                    </Button>
                    <Tooltip :content="viewImg" placement="bottom-start">
                        <Poptip>
                            <Icon type="md-help-circle" class="excel-help"/>
                            <div class="box-img" slot="content">
                                <img src="../../../../assets/images/tupian2.png" class="img-style">
                            </div>
                        </Poptip>
                    </Tooltip>
                    <Button v-has="'CL_shujudaoru'" type="primary" class="mp10" :disabled="excelBtnDisabled"
                            @click="importExcel(row)">数据导入
                    </Button>
                    <Tooltip :content="excelBtnDescribe" placement="bottom-start" v-if="excelBtnDisabled"
                             max-width="400" class="mp10">
                        <Icon type="md-help-circle" class="excel-help"/>
                    </Tooltip>
                    <Select @on-change="flagSelChange" placeholder="请选择数量符合状态" class="select-class"
                            v-model="imgNumFlagSelect">
                        <Option value="1">全部</Option>
                        <Option value="2">一致</Option>
                        <Option value="3">不一致</Option>
                    </Select>
                </template>
                <template>
                    <Input type="text" @on-enter="searchAction" placeholder="请输入材料名称" v-model="params.title"
                           icon="ios-search" class="input-class"/>
                </template>
            </template>
        </vxe-toolbar>
        <vxe-table
                border
                resizable
                show-overflow
                ref="xTable"
                size="medium"
                max-height="500"
                align="center"
                :edit-rules="validRules"
                class="my_table_insert"
                :loading='tableLoading'
                :data="tableData"
                :cell-style="cellStyle"
                :tooltip-config="{theme:'light',enterable:true}"
                @edit-actived="editActivedEvent"
                @edit-closed="editClosedEvent"
                @edit-disabled="editDisabledEvent"
                :edit-config="{trigger: 'click', mode: 'row', icon: 'fa fa-pencil', activeMethod: activeRowMethod}">
            <vxe-table-column type="checkbox" width="60"></vxe-table-column>
            <vxe-table-column type="seq" width="60"></vxe-table-column>
            <vxe-table-column field="record_number" title="全宗号" width="100"></vxe-table-column>
            <vxe-table-column field="serial_number" title="流水号" width="100" ></vxe-table-column>
            <vxe-table-column field="name" title="姓名" width="100"></vxe-table-column>
            <vxe-table-column field="idcard" title="身份证号" width="200"></vxe-table-column>
            <vxe-table-column field="create_time" title="创建时间" width="150"></vxe-table-column>
            <vxe-table-column
                    field="remark"
                    title="备注"
                    min-width="200"
                    :edit-render="{name: 'input',attrs:{placeholder:'输入备注'}}"
            >
            </vxe-table-column>
            <vxe-table-column
                    field="formate_time"
                    title="形成时间"
                    min-width="200"
                    :edit-render="{name: 'input',attrs:{placeholder:'输入形成时间'}}"
            >
            </vxe-table-column>
            <vxe-table-column
                    field="title"
                    title="材料名称"
                    min-width="200"
                    :filters="[{ data: '' }]"
                    :filter-method="filterTitleMethod"
                    :edit-render="{name: 'input',attrs:{placeholder:'输入材料名称'}}">
                <template v-slot:filter="{ $panel, column }">
                    <input type="type" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
                           @input="$panel.changeOption($event, !!option.data, option)">
                </template>
            </vxe-table-column>
            <vxe-table-column
                    field="dir"
                    title="文件夹名(序号)"
                    min-width="200"
                    :edit-render="{name: 'input',attrs:{placeholder:'如1-1'}}">
            </vxe-table-column>
            <vxe-table-column title="更新中" width="200" v-if="updateImgAwait">
                <template v-slot="{ row }">
                    <div v-show="row.img_progress<100">
                        <Progress :percent="row.img_progress"/>
                    </div>
                    <div v-show="row.img_progress==100">{{ row.img_msg }}</div>
                </template>
            </vxe-table-column>
            <vxe-table-column
                    field="num"
                    title="页数"
                    min-width="100"
                    :edit-render="{name: 'input',attrs:{placeholder:'如 5'}}">
            </vxe-table-column>
            <vxe-table-column
                    field="imgList"
                    title="图片内容"
                    :filters="[{label: '已上传图片', value: '1'}, {label: '未上传图片', value: '0'}, {label: '数量不正确', value: '2'}]"
                    :filter-method="filterImgPathMethod"
                    :filter-multiple="false"
                    min-width="200"
                    fixed="right">
                <template v-slot="{ row, rowIndex }">
                    <Button v-has="'CL_view'" class="btn-action" type="primary" size="small" @click="showImgListAction(row)">查看[{{
                        row.imgListCount }}]
                    </Button>
                    <Button v-has="'CL_viewAll'" class="btn-action" type="primary" size="small" @click="showImgAllAction(row, rowIndex)">
                        查看所有
                    </Button>
                </template>
            </vxe-table-column>
            <vxe-table-column title="操作" fixed="right" min-width="100" v-if="row.state == 1 || row.state == 4">
                <template v-slot="{ row }">
                    <Button v-has="'CL_editImg'" type="success" size="small" @click="uploadImgAll(row)">编辑图片</Button>
                </template>
            </vxe-table-column>
        </vxe-table>
    </div>
</template>
<script>
import {
  getMaterialTypePersonalNum,
  getPersonalMaterialList,
  getRecordById,
  savePersonalMaterial,
  delMaterialAll,
  updateCLState
} from '@/api/record'
import { isNumber } from '@/libs/util'
import ImportDirImg from './import-dir-img/index'
import ViewerShowImg from './viewer-show-img/index'
import ImportImgs from './import-imgs/index'
import { mapActions } from 'vuex'
export default {
  components: { ImportImgs, ViewerShowImg, ImportDirImg },
  data () {
    const dirValid = ({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) => {
      return new Promise((resolve, reject) => {
        if (cellValue === '' || cellValue === 'undefined' || cellValue === undefined || cellValue === ' ') {
          reject(new Error('表单项不能为空'))
        } else {
          let arr2 = cellValue.split('-')
          if (arr2.length <= 1) {
            reject(new Error('文件夹命名不正确，缺少`-`'))
          } else {
            arr2.forEach(item => {
              if (!isNumber(item)) {
                reject(new Error('名称只能是数字'))
              }
            })
          }
          resolve()
        }
      })
    }
    const numValid = ({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) => {
      return new Promise((resolve, reject) => {
        if (!isNumber(cellValue)) {
          reject(new Error('图片数量只能是数字'))
        } else {
          resolve()
        }
      })
    }
    const titleValid = ({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) => {
      return new Promise((resolve, reject) => {
        if (cellValue === '' || cellValue === 'undefined' || cellValue === undefined || cellValue === ' ') {
          reject(new Error('材料名称不能为空！'))
        } else {
          resolve()
        }
      })
    }
    return {
      imgNumFlagSelect: '',
      row: {},
      barData: {},
      pageNum: 0,
      countData: { loading: true, imgTotal: 0, total: 0, rightNum: 0 }, // 前台数量统计（废弃）
      params: { archive_id: '', title: '' },
      tableData: [],
      selection: [],
      tableLoading: true,
      validRules: {
        title: [
          { validator: titleValid }
        ],
        dir: [
          { validator: dirValid }
        ],
        num: [
          { validator: numValid }
        ]
      },
      openEditRow: {},
      updateImgAwait: false,
      showImgList: [],
      excelBtnDisabled: true,
      excelBtnDescribe: '仅在无数据时开启，若导入数据请先删除全部数据',
      viewImg: '点击可查看导入图片文件夹命名格式',
      troubleColor: {
        cellColor: '#ED4014',
        cellBgColor: '#FFEFE6',
        cellRepeatColor: '#fff',
        cellRepeatBgColor: '#187'
      },
      cloneTableData: [],
      viewShow: true, // viewer显示状态
      imgALlList: [], // 所有图片数据
      removeRecords: []// 选中的数组
    }
  },
  methods: {
    ...mapActions([
      'appendBreadCrumb'
    ]),
    // 错误问题样式
    cellStyle ({ row, rowIndex, column, columnIndex }) {
      if (!row.imgNumFlag) {
        return {
          color: this.troubleColor.cellColor,
          backgroundColor: this.troubleColor.cellBgColor
        }
      }
    },
    flagSelChange (val) {
      let arr = []
      switch (val) {
        case '1':
          this.tableData = this.cloneTableData
          break
        case '2':
          this.cloneTableData.forEach(item => {
            if (item.imgNumFlag) {
              arr.push(item)
            }
          })
          this.tableData = arr
          break
        case '3':
          this.cloneTableData.forEach(item => {
            if (!item.imgNumFlag) {
              arr.push(item)
            }
          })
          this.tableData = arr
          break
      }
    },
    initAction () {
      this.getList()
      this.getMaterialTypePersonalNumAction()
    },
    getMaterialTypePersonalNumAction () {
      getMaterialTypePersonalNum(this.$route.query.id).then(ret => {
        if (ret.data.errcode === 0) {
          this.barData = ret.data.data
        } else {
          this.$Message.error('获取统计数量失败，请检查网络！')
        }
      })
    },
    filterTitleMethod ({ option, row }) {
      return row.title && row.title.indexOf(option.data) !== -1
    },
    filterImgPathMethod ({ option, row }) {
      if (option.value === '1') {
        return row.imgList.length > 0
      } else if (option.value === '0') {
        return row.imgList.length === 0
      } else {
        return row.imgList.length > 0 && row.imgList.length !== row.num
      }
    },
    importImgsResultAction (path, row) {
      // console.log(path, '单条', row)
      if (path !== row.img_path) {
        this.saveMaterialIMGAction({ id: row.id, num: row.num, img_path: path }).then(ret => {
          if (ret.errcode === 0) {
            this.$Message.success('更新成功！')
            this.initAction()
          } else {
            this.$Message.error('更新失败！！')
            this.initAction()
          }
        })
      }
    },
    imgResultAction (data) {
      // console.log('批量', data)
      this.updateImgAwait = true
      this.tableData.forEach((item, index) => {
        item.img_progress = 10
        if (data[item.dir]) {
          let img_path = data[item.dir].map(items => {
            return items.path
          })
          this.saveMaterialIMGAction({
            id: item.id,
            num: item.num,
            img_path: img_path.toString()
          }, 'edit').then(ret => {
            if (ret.errcode === 0) {
              item.img_progress = 100
              item.img_msg = '总共更新了' + data[item.dir].length + '张图片'
              this.$set(this.tableData, index, item)
              this.initAction()
            } else {
              item.img_progress = 100
              item.img_msg = '更新失败，需要手动上传'
              this.$set(this.tableData, index, item)
              this.initAction()
            }
          })
        } else {
          item.img_progress = 100
          item.img_msg = '没有更新'
        }
      })
    },
    getPeopleInfo () {
      getRecordById(this.$route.query.id).then(ret => {
        if (ret.data.errcode === 0) {
          this.row = ret.data.data
        } else {
          this.$Message.error('获取信息失败，请检查网络！')
        }
      })
    },
    getList (val) {
      // console.log('初始化列表')
      this.tableLoading = true
      getPersonalMaterialList(this.params).then(res => {
        this.tableLoading = false
        let result = res.data.data
        if (res.data.errcode === 0) {
          this.tableData = res.data.data
          this.excelBtnDisabled = this.tableData.length > 0 || (val === 'search' && this.params.title !== '')
          this.showImgList = []
          this.pageNum = 0
          result.forEach(item => {
            if (item.num) this.pageNum += parseInt(item.num)
            if (item.img_path) {
              this.countData.imgTotal++
              item.img_path = (item.img_path.substring(item.img_path.length - 1) === ',') ? item.img_path.substring(0, item.img_path.length - 1) : item.img_path
              item.imgList = item.img_path.split(',')
              item.imgListCount = item.imgList.length
              if (item.imgList[item.imgList.length - 1] === '') {
                item.imgListCount = item.imgList.length - 1
              }
              if (item.imgList.length === item.num) {
                this.countData.rightNum++
                item.imgNumFlag = true
              } else {
                item.imgNumFlag = false
              }
            } else {
              item.img_path = ''
              item.imgListCount = 0
              item.imgList = []
              item.imgNumFlag = false
            }
            // 查看图片数据处理（排序）
            let arr = []
            item.imgList.forEach(item2 => {
              if (item2 !== '') arr.push({ url: item2, name: this.autoSubString(item2, '/', '.jpg') })
            })
            item.imgList = this.$common.xeUtils.sortBy(arr, 'name')
            // 组装全部图片数据
            item.imgList.forEach(item3 => {
              this.imgALlList.push(item3)
            })
          })
          // this.params.totalRecord = result.totalRecord
          this.countData.loading = false
          this.countData.total = result.totalRecord
          this.cloneTableData = this.$common.xeUtils.clone(this.tableData, true)
        }
      })
    },
    searchAction () {
      this.params.pageNo = 1
      this.getList('search')
    },
    // 查看单材料图片
    showImgListAction (row) {
      this.viewShow = true
      this.$refs.viewerShowImg.showLoading()
      this.showImgList = row.imgList
      this.$refs.viewerShowImg.showLoading()
    },
    // 查看所有图片
    showImgAllAction (row, index) {
      this.viewShow = false
      this.showImgList = this.imgALlList
      let count = 0
      for (let i = 0; i < this.tableData.length; i++) {
        if (i < index) count += this.tableData[i].imgList.length
      }
      this.$refs.viewerShowImg.show(count)
    },
    // 截取字符串
    autoSubString (str, firstStr, secondStr) {
      if (str === '' || str == null || str === undefined) {
        return ''
      }
      if (str.indexOf(firstStr) < 0) {
        return ''
      }
      let subFirstStr = str.substring(str.indexOf(firstStr) + firstStr.length, str.length)
      let subSecondStr = subFirstStr.substring(0, subFirstStr.indexOf(secondStr))
      if (subSecondStr.indexOf('/') !== -1) {
        let orignStr = subSecondStr.substring(subSecondStr.lastIndexOf('/') + 1, subSecondStr.length)
        let newArr = orignStr.split('-').reverse()
        let newArr2 = []
        newArr.forEach(item => {
          if (parseInt(item) < 10) {
            newArr2.push('0' + item)
          } else {
            newArr2.push(item)
          }
        })
        let newArr3 = newArr2.reverse().join('-')
        return newArr3
      } else {
        return subSecondStr
      }
    },
    async saveMaterialAction (data, type) {
      let postData = {}
      postData = data
      let ret = await savePersonalMaterial(postData)
      if (ret !== undefined && ret !== 'undefined') {
        if (ret.data.errcode !== 0) {
          this.$Message.error(ret.data.errmsg)
        } else {
          ret = ret.data
        }
      } else {
        this.$Message.error('请检查网络！！！')
        ret = { data: { errcode: 100 } }
      }
      return ret
    },
    async saveMaterialIMGAction (data, type) {
      let postData = {}
      postData = data
      let ret = await updateCLState(postData)
      if (ret !== undefined && ret !== 'undefined') {
        if (ret.data.errcode !== 0) {
          this.$Message.error(ret.data.errmsg)
        } else {
          ret = ret.data
        }
      } else {
        this.$Message.error('请检查网络！！！')
        ret = { data: { errcode: 100 } }
      }
      return ret
    },
    async deleteRowList (row) {
      // console.log(row, this.$refs.xTable.getCheckboxRecords(), '选中的内容')
      this.removeRecords = this.$refs.xTable.getCheckboxRecords()
      if (this.removeRecords.length === 0) {
        this.$Message.error('请选择要删除的数据！')
        return false
      }
      this.$Modal.confirm({
        title: '确认删除此档案信息吗？',
        content: '删除后不可恢复，请确认后再操作！',
        onOk: () => {
          let postData = { del_flag: 1 }
          postData.ids = this.removeRecords.map(item => {
            return item.id
          })
          delMaterialAll(postData).then(result => {
            if (result.data.errcode === 0) {
              this.$Message.success('操作成功！')
              // this.$refs.xTable.removeSelecteds()
              this.$refs.xTable.removeCheckboxRow()
              this.initAction()
            } else {
              this.$Message.error(result.data.errmsg)
              // this.$refs.xTable.removeSelecteds()
              this.$refs.xTable.removeCheckboxRow()
              this.initAction()
            }
          })
        }
      })
    },
    uploadImgDirAll (row, what) {
      this.$refs.imgDirService.modelAction()
    },
    uploadImgAll (row, what) {
      if (!row.title || row.title === '') {
        this.$Message.error('请先完善材料名称')
        return false
      }
      if (!row.dir || row.dir === '') {
        this.$Message.error('请先完善文件夹名称')
        return false
      }
      this.$refs.imgService.modelAction(row)
    },
    backAction () {
      if (this.$route.query.type && this.$route.query.type === 'accept') {
        this.$router.push({ name: 'recordAppear', params: { options: this.$route.params.options } })
      } else {
        this.$router.push({ name: 'recordList' })
      }
    },
    importExcel (row) {
      if (row.record_number) {
        this.$router.push({
          name: 'recordExcel',
          query: { type: 'material', archive_id: this.$route.query.id }
        })
      } else {
        this.$Message.warning('缺少全宗号！')
      }
    },
    async insertEvent (row) {
      let record = {
        record_number: row.record_number,
        serial_number: row.serial_number,
        name: row.name,
        idcard: row.idcard,
        archive_id: row.id,
        img_path: ''
      }
      let retsult = await this.saveMaterialAction(record)
      record.id = retsult.data.uuid
      let { row: newRow } = await this.$refs.xTable.insertAt(record)
      await this.$refs.xTable.setActiveCell(newRow, 'title')
    },
    editActivedEvent ({ row, column }, event) {
      this.openEditRow = this.$common.xeUtils.clone(row)
      // console.log('edit数据', this.openEditRow)
    },
    async editClosedEvent ({ row, column }, event) {
      const errMap = await this.$refs.xTable.validate().catch(errMap => errMap)
      if (errMap) {
        this.$Message.error('请正确填写数据！')
      } else {
        if (!this.$common.xeUtils.isEqual(this.openEditRow, row)) {
          this.saveMaterialIMGAction(row, 'edit').then(ret => {
            if (ret.errcode === 0) {
              this.$Message.success('编辑成功！')
              this.initAction()
            } else {
              this.$Message.error('编辑失败！')
              this.initAction()
            }
          })
        }
      }
    },
    activeRowMethod () {
      // 针对已经提报后数据不可编辑处理
      return this.row.state === '1' || this.row.state === '4'
    },
    editDisabledEvent ({ row, column }) {
      this.$Message.error('数据已经提报不可编辑！')
    }
  },
  mounted () {
    if (this.$route.query.id) {
      this.params.archive_id = this.$route.query.id
      this.params.type = this.$route.query.type
      this.getPeopleInfo()
      this.initAction()
      if (this.$store.getters.getBreadCrumbList.length < 2) {
        this.appendBreadCrumb({
          id: 'a9689901',
          title: '材料管理',
          path: '/record/materials?id=' + this.$route.query.id,
          icon: '33'
        })
      }
    } else {
      this.$Message.error('页面缺少参数')
      this.$router.push({ name: 'recordList' })
    }
  }
}
</script>

<style scoped>
    .input-class {
        width: 200px;
        display: inline-block;
    }

    .excel-help {
        margin-right: 10px;
        color: orange;
        cursor: pointer;
    }

    /deep/ .ivu-poptip-inner {
        width: 900px;
    }

    .img-style {
        width: 100%;
    }

    .page_style {
        margin: 20px 5px;
    }

    .input-frame {
        width: 120px;
        margin-right: 10px;
    }

    .house-list > .group {
        background: white;
        padding: 10px;
        margin-top: 10px;
    }

    .house-list > .group > .item {
        border-bottom: 1px solid #f5f5f5;
        padding: 10px 0;
    }

    .house-list > .group > .item .top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
    }

    .house-list > .group > .item .title {
        font-size: 14px;
        color: #333333;
    }

    .house-list > .group > .item .address {
        font-size: 12px;
        color: gray;
        display: flex;
        align-items: center;
    }

    .house-list > .group > .item .detail {
        font-size: 12px;
        color: dodgerblue;
    }

    .opt-area-02 {
        display: flex;
        align-items: center;
        flex-direction: column;
        border: 1px solid #abdcff;
        background-color: #f0faff;
        padding: 8px 16px 8px 16px;
        border-radius: 4px;
        margin-bottom: 10px;
    }

    .opt-area-02 .right-con {
        width: 100%;
        margin-top: 5px;
        display: flex;
    }

    .opt-area-02 .left-con {
        font-size: 14px;
        width: 100%;
    }

    .opt-area-02 .left-con span {
        font-weight: bold;
    }

    .opt-area-02 .right-con input {
        width: 150px;
        margin-right: 10px;
    }

    .opt-area-02 .right-con .input-frame {
        width: 200px;
        margin-right: 10px;
    }

    .table-action-btn {
        margin-right: 3px;
    }

    .container >>> .ivu-btn-small {
        height: 24px;
        padding: 0 5px;
        font-size: 12px;
        border-radius: 3px;
    }

    .btn-action {
        /*margin-bottom: 10px;*/
        margin-right: 10px;
    }

    .mp10 {
        margin-right: 10px;
    }

    .select-class {
        display: inline-block;
        width: 200px;
        margin-right: 10px;
    }

    .my_table_insert >>> .row--new {
        background-color: #f1fdf1;
    }

    .container >>> .vxe-table--loading {
        background-color: rgba(249, 246, 246, 0.2);
    }

    .container >>> .vxe-table--loading .vxe-table--spinner {
        width: 40px;
        height: 40px;
    }
</style>
